/*
 * DocViewView.java
 */

package docview;

import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Toolkit;
import java.io.IOException;
import java.util.logging.Level;
import javax.swing.event.TreeModelEvent;
import javax.swing.tree.MutableTreeNode;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import service.PropertiesManager;
import tableprocessor.PriceDAO;
import tableprocessor.SessionFactoryUtil;
import tableprocessor.StaticLogContainer;
import org.slf4j.Logger;
import tableprocessor.MicrosoftOfficeFilesProcessor;

/**
 * The application's main frame.
 */
public class DocViewView extends FrameView implements TreeModelListener{

    public DocViewView(SingleFrameApplication app) {
        super(app);
        this.getFrame().setTitle("DocView v_1.0");
        initComponents();
       CathegoryTree.getModel().addTreeModelListener(this);
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int w = (int) (dim.getWidth() / 2);
        int h = (int) (dim.getHeight() / 2);
        int x = (int) (dim.getWidth()/2 - w/2);
        int y = (int) (dim.getHeight()/2 - h/2);
        this.getFrame().setBounds(x, y, w, h);
       
        // StaticLogContainer.redirectOutput(historyTextArea);
       // StaticLogContainer.redirectErr(historyTextArea);
       // StaticLogContainer.redirectOut(historyTextArea);


    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = DocViewApp.getApplication().getMainFrame();
            aboutBox = new DocViewAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        DocViewApp.getApplication().show(aboutBox);
    }
    //***********************************************************
    //********************ACTIONS********************************
    //***********************************************************
    @Action
    public void showPropertiesBox()
    {
        OptionsFrame.setTitle("Настройки");
        OptionsFrame.setVisible(true);
    }
    @Action
    public void saveResultPrice()
    {
        MicrosoftOfficeFilesProcessor ofproc = new MicrosoftOfficeFilesProcessor();
        File file;
        JFileChooser fc = new JFileChooser();
        if (fc.showSaveDialog(null)==0)
        {
            file = fc.getSelectedFile();
            ofproc.saveToDoc(file.getAbsolutePath());
        }
    }
    @Action
    public void loadPrice()
    {
        OpenAddPriceFrame pf = new OpenAddPriceFrame(manager);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int w = (int) (dim.getWidth() / 3);
        int h = (int) (dim.getHeight() / 3);
        int x = (int) (dim.getWidth()/2 - w/2);
        int y = (int) (dim.getHeight()/2 - h/2);
        pf.setBounds(x, y, w, h);
        pf.setVisible(true);
    }
    @Action
    public void showCathegoryBox()
    {
        CathegoryFrame.setTitle("Редактор категорий");
        CathegoryFrame.setVisible(true);
    }
    //***********************************************************
    //***********************************************************
    //***********************************************************
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        historyTextArea = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        historyTree = new javax.swing.JTree();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        LoadPriceItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        ToolsMenu = new javax.swing.JMenu();
        MenuOptionsItem = new javax.swing.JMenuItem();
        CategoryEditMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        styleEditorMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        savePriceMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        OptionsFrame = new javax.swing.JFrame();
        DBServerField = new javax.swing.JTextField();
        DBLoginField = new javax.swing.JTextField();
        DBPasswordField = new javax.swing.JPasswordField();
        OptionsButtonPanel = new javax.swing.JPanel();
        OptionsFrameSaveButton = new javax.swing.JButton();
        OptionsFrameCancelButton = new javax.swing.JButton();
        CathegoryFrame = new javax.swing.JFrame();
        TreeScrollPane = new javax.swing.JScrollPane();
        CathegoryTree = new javax.swing.JTree();
        ThtreeButtonPanel = new javax.swing.JPanel();
        ButtonPanel = new javax.swing.JPanel();
        TreeAddButton = new javax.swing.JButton();
        TreeDeleteButton = new javax.swing.JButton();
        TreeAddColButton = new javax.swing.JButton();
        TreeRemoveColButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        TreeSaveButton = new javax.swing.JButton();
        TreeCancelButton = new javax.swing.JButton();
        TextPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TreeTextArea = new javax.swing.JTextArea();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setLayout(new java.awt.GridLayout(1, 1));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(docview.DocViewApp.class).getContext().getResourceMap(DocViewView.class);
        jSplitPane1.setToolTipText(resourceMap.getString("jSplitPane1.toolTipText")); // NOI18N
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        historyTextArea.setColumns(20);
        historyTextArea.setFont(resourceMap.getFont("historyTextArea.font")); // NOI18N
        historyTextArea.setRows(5);
        historyTextArea.setName("historyTextArea"); // NOI18N
        jScrollPane2.setViewportView(historyTextArea);

        jSplitPane1.setRightComponent(jScrollPane2);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Изменения");
        historyTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        historyTree.setName("historyTree"); // NOI18N
        jScrollPane3.setViewportView(historyTree);

        jSplitPane1.setLeftComponent(jScrollPane3);

        mainPanel.add(jSplitPane1);

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(docview.DocViewApp.class).getContext().getActionMap(DocViewView.class, this);
        LoadPriceItem.setAction(actionMap.get("loadPrice")); // NOI18N
        LoadPriceItem.setText(resourceMap.getString("LoadPriceItem.text")); // NOI18N
        LoadPriceItem.setName("LoadPriceItem"); // NOI18N
        fileMenu.add(LoadPriceItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        ToolsMenu.setAction(actionMap.get("showPropertiesBox")); // NOI18N
        ToolsMenu.setText(resourceMap.getString("ToolsMenu.text")); // NOI18N
        ToolsMenu.setName("ToolsMenu"); // NOI18N

        MenuOptionsItem.setAction(actionMap.get("showPropertiesBox")); // NOI18N
        MenuOptionsItem.setText(resourceMap.getString("MenuOptionsItem.text")); // NOI18N
        MenuOptionsItem.setName("MenuOptionsItem"); // NOI18N
        ToolsMenu.add(MenuOptionsItem);

        CategoryEditMenuItem.setAction(actionMap.get("showCathegoryBox")); // NOI18N
        CategoryEditMenuItem.setText(resourceMap.getString("CategoryEditMenuItem.text")); // NOI18N
        CategoryEditMenuItem.setName("CategoryEditMenuItem"); // NOI18N
        ToolsMenu.add(CategoryEditMenuItem);

        menuBar.add(ToolsMenu);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        styleEditorMenuItem.setText(resourceMap.getString("styleEditorMenuItem.text")); // NOI18N
        styleEditorMenuItem.setName("styleEditorMenuItem"); // NOI18N
        jMenu1.add(styleEditorMenuItem);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jMenu1.add(jSeparator2);

        savePriceMenuItem.setAction(actionMap.get("saveResultPrice")); // NOI18N
        savePriceMenuItem.setText(resourceMap.getString("savePriceMenuItem.text")); // NOI18N
        savePriceMenuItem.setName("savePriceMenuItem"); // NOI18N
        jMenu1.add(savePriceMenuItem);

        menuBar.add(jMenu1);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        OptionsFrame.setBounds(new java.awt.Rectangle(100, 100, 300, 250));
        OptionsFrame.setName("OptionsFrame"); // NOI18N
        OptionsFrame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                OptionsFrameWindowActivated(evt);
            }
        });
        OptionsFrame.getContentPane().setLayout(new java.awt.GridLayout(4, 2, 2, 2));

        DBServerField.setBackground(OptionsFrame.getBackground());
        DBServerField.setText(resourceMap.getString("DBServerField.text")); // NOI18N
        DBServerField.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("DBServerField.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); // NOI18N
        DBServerField.setName("DBServerField"); // NOI18N
        OptionsFrame.getContentPane().add(DBServerField);

        DBLoginField.setBackground(OptionsFrame.getBackground());
        DBLoginField.setText(resourceMap.getString("DBLoginField.text")); // NOI18N
        DBLoginField.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("DBLoginField.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); // NOI18N
        DBLoginField.setName("DBLoginField"); // NOI18N
        OptionsFrame.getContentPane().add(DBLoginField);

        DBPasswordField.setBackground(OptionsFrame.getBackground());
        DBPasswordField.setText(resourceMap.getString("DBPasswordField.text")); // NOI18N
        DBPasswordField.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("DBPasswordField.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); // NOI18N
        DBPasswordField.setName("DBPasswordField"); // NOI18N
        OptionsFrame.getContentPane().add(DBPasswordField);

        OptionsButtonPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        OptionsButtonPanel.setName("OptionsButtonPanel"); // NOI18N
        OptionsButtonPanel.setLayout(new java.awt.GridLayout(1, 2, 5, 10));

        OptionsFrameSaveButton.setText(resourceMap.getString("OptionsFrameSaveButton.text")); // NOI18N
        OptionsFrameSaveButton.setName("OptionsFrameSaveButton"); // NOI18N
        OptionsFrameSaveButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                OptionsFrameSaveButtonMouseClicked(evt);
            }
        });
        OptionsButtonPanel.add(OptionsFrameSaveButton);

        OptionsFrameCancelButton.setText(resourceMap.getString("OptionsFrameCancelButton.text")); // NOI18N
        OptionsFrameCancelButton.setName("OptionsFrameCancelButton"); // NOI18N
        OptionsFrameCancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                OptionsFrameCancelButtonMouseClicked(evt);
            }
        });
        OptionsButtonPanel.add(OptionsFrameCancelButton);

        OptionsFrame.getContentPane().add(OptionsButtonPanel);

        CathegoryFrame.setBounds(new java.awt.Rectangle(100, 100, 300, 400));
        CathegoryFrame.setName("CathegoryFrame"); // NOI18N
        CathegoryFrame.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                CathegoryFrameComponentShown(evt);
            }
        });
        CathegoryFrame.getContentPane().setLayout(new java.awt.GridLayout(1, 2));

        TreeScrollPane.setName("TreeScrollPane"); // NOI18N

        CathegoryTree.setBackground(resourceMap.getColor("CathegoryTree.background")); // NOI18N
        CathegoryTree.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Категории");
        CathegoryTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        CathegoryTree.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        CathegoryTree.setDropMode(javax.swing.DropMode.ON_OR_INSERT);
        CathegoryTree.setEditable(true);
        CathegoryTree.setLargeModel(true);
        CathegoryTree.setName("CathegoryTree"); // NOI18N
        CathegoryTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                CathegoryTreeValueChanged(evt);
            }
        });
        TreeScrollPane.setViewportView(CathegoryTree);

        CathegoryFrame.getContentPane().add(TreeScrollPane);

        ThtreeButtonPanel.setName("ThtreeButtonPanel"); // NOI18N
        ThtreeButtonPanel.setLayout(new java.awt.GridLayout(2, 1));

        ButtonPanel.setName("ButtonPanel"); // NOI18N
        ButtonPanel.setLayout(new java.awt.GridLayout(7, 1));

        TreeAddButton.setText(resourceMap.getString("TreeAddButton.text")); // NOI18N
        TreeAddButton.setMaximumSize(TreeAddButton.getPreferredSize());
        TreeAddButton.setName("TreeAddButton"); // NOI18N
        TreeAddButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TreeAddButtonMouseClicked(evt);
            }
        });
        ButtonPanel.add(TreeAddButton);

        TreeDeleteButton.setText(resourceMap.getString("TreeDeleteButton.text")); // NOI18N
        TreeDeleteButton.setName("TreeDeleteButton"); // NOI18N
        TreeDeleteButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TreeDeleteButtonMouseClicked(evt);
            }
        });
        ButtonPanel.add(TreeDeleteButton);

        TreeAddColButton.setText(resourceMap.getString("TreeAddColButton.text")); // NOI18N
        TreeAddColButton.setName("TreeAddColButton"); // NOI18N
        TreeAddColButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TreeAddColButtonMouseClicked(evt);
            }
        });
        ButtonPanel.add(TreeAddColButton);

        TreeRemoveColButton.setText(resourceMap.getString("TreeRemoveColButton.text")); // NOI18N
        TreeRemoveColButton.setName("TreeRemoveColButton"); // NOI18N
        TreeRemoveColButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TreeRemoveColButtonMouseClicked(evt);
            }
        });
        ButtonPanel.add(TreeRemoveColButton);

        jSeparator1.setName("jSeparator1"); // NOI18N
        ButtonPanel.add(jSeparator1);

        TreeSaveButton.setText(resourceMap.getString("TreeSaveButton.text")); // NOI18N
        TreeSaveButton.setActionCommand(resourceMap.getString("TreeSaveButton.actionCommand")); // NOI18N
        TreeSaveButton.setName("TreeSaveButton"); // NOI18N
        TreeSaveButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TreeSaveButtonMouseClicked(evt);
            }
        });
        ButtonPanel.add(TreeSaveButton);

        TreeCancelButton.setText(resourceMap.getString("TreeCancelButton.text")); // NOI18N
        TreeCancelButton.setName("TreeCancelButton"); // NOI18N
        TreeCancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TreeCancelButtonMouseClicked(evt);
            }
        });
        ButtonPanel.add(TreeCancelButton);

        ThtreeButtonPanel.add(ButtonPanel);

        TextPanel.setName("TextPanel"); // NOI18N
        TextPanel.setLayout(new java.awt.GridLayout(1, 1));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        TreeTextArea.setBackground(CathegoryFrame.getBackground());
        TreeTextArea.setColumns(20);
        TreeTextArea.setFont(resourceMap.getFont("TreeTextArea.font")); // NOI18N
        TreeTextArea.setRows(5);
        TreeTextArea.setEnabled(false);
        TreeTextArea.setName("TreeTextArea"); // NOI18N
        jScrollPane1.setViewportView(TreeTextArea);

        TextPanel.add(jScrollPane1);

        ThtreeButtonPanel.add(TextPanel);

        CathegoryFrame.getContentPane().add(ThtreeButtonPanel);

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void OptionsFrameSaveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_OptionsFrameSaveButtonMouseClicked
        
        if (!PropertiesManager.setDBPath(DBServerField.getText())||
          //  !PropertiesManager.setDBName(DBNameField.getText())||
            !PropertiesManager.setDBLogin(DBLoginField.getText())||
            !PropertiesManager.setDBPassword(DBPasswordField.getText()))
            {
                    JOptionPane.showMessageDialog(null, "Ошибка сохранения настроек ");
            }
    else
        {
            SessionFactoryUtil.reload();
        }
        OptionsFrame.setVisible(false);
    }//GEN-LAST:event_OptionsFrameSaveButtonMouseClicked

    private void OptionsFrameCancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_OptionsFrameCancelButtonMouseClicked
        OptionsFrame.setVisible(false);
    }//GEN-LAST:event_OptionsFrameCancelButtonMouseClicked

    private void OptionsFrameWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_OptionsFrameWindowActivated
        if (!PropertiesManager.isOk())
        {
            OptionsFrame.setVisible(false);
            JOptionPane.showMessageDialog(null, "Не могу найти файл настроек hibernate.cfg.xml "
                    + "или его структура неверна");
        }
        else
        {
            DBServerField.setText(PropertiesManager.getDBPath());
         //   DBNameField.setText(PropertiesManager.getDBName());
            DBLoginField.setText(PropertiesManager.getDBLogin());
            DBPasswordField.setText(PropertiesManager.getDBPassword());
        }
    }//GEN-LAST:event_OptionsFrameWindowActivated

    private void CathegoryFrameComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_CathegoryFrameComponentShown
      CathegoryTree.setModel(priceDAO.getTree().getModel());
      CathegoryTree.getModel().addTreeModelListener(this);
    }//GEN-LAST:event_CathegoryFrameComponentShown

    private void CathegoryTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_CathegoryTreeValueChanged

        if (evt.getNewLeadSelectionPath()!=null)
        {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)evt.getNewLeadSelectionPath().getLastPathComponent();
            if (node!=null)
            TreeTextArea.setText(node.toString());
        }
    }//GEN-LAST:event_CathegoryTreeValueChanged

    private void TreeCancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TreeCancelButtonMouseClicked
        CathegoryFrame.setVisible(false);
    }//GEN-LAST:event_TreeCancelButtonMouseClicked

    private void TreeSaveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TreeSaveButtonMouseClicked
        CathegoryTree.setModel(priceDAO.getTree().getModel());
        CathegoryTree.getModel().addTreeModelListener(this);
       // CathegoryFrame.setVisible(false);
    }//GEN-LAST:event_TreeSaveButtonMouseClicked

    private void TreeAddButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TreeAddButtonMouseClicked
        String name = JOptionPane.showInputDialog("Введите название категории : ");
        if (name != null && !name.isEmpty() && CathegoryTree.getSelectionPath()!=null)
        {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)CathegoryTree.getSelectionPath().getLastPathComponent();
                priceDAO.addCathegory(node, name);
                CathegoryTree.setModel(priceDAO.getTree().getModel());
                CathegoryTree.getModel().addTreeModelListener(this);
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Категория не добавлена");
        }

    }//GEN-LAST:event_TreeAddButtonMouseClicked

    private void TreeDeleteButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TreeDeleteButtonMouseClicked
       if (JOptionPane.showConfirmDialog(null, "Вы уверены?") == 0 )
       {
           if (CathegoryTree.getSelectionPath()!=null)
           {
                if (!priceDAO.removeCathegory((DefaultMutableTreeNode)CathegoryTree.getSelectionPath().getLastPathComponent())&&
                        priceDAO.isColumn((DefaultMutableTreeNode)CathegoryTree.getSelectionPath().getLastPathComponent()))
                {
                    JOptionPane.showMessageDialog(null,"Невозможно удалить категорию");

                }
                else
                {
                    CathegoryTree.setModel(priceDAO.getTree().getModel());
                    CathegoryTree.getModel().addTreeModelListener(this);
                }
           }
           else
           {
               JOptionPane.showMessageDialog(null,"Не выбрана категория");
           }

       }
    }//GEN-LAST:event_TreeDeleteButtonMouseClicked

    private void TreeAddColButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TreeAddColButtonMouseClicked
        String name = JOptionPane.showInputDialog("Введите имя столбца : ");
        if (name != null && !name.isEmpty() && CathegoryTree.getSelectionPath()!=null)
        {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)CathegoryTree.getSelectionPath().getLastPathComponent();
            priceDAO.addColumn(node, name);
            CathegoryTree.setModel(priceDAO.getTree().getModel());
            CathegoryTree.getModel().addTreeModelListener(this);
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Поле не добавленo");
        }
        
    }//GEN-LAST:event_TreeAddColButtonMouseClicked

    private void TreeRemoveColButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TreeRemoveColButtonMouseClicked
      if (JOptionPane.showConfirmDialog(null, "Вы уверены?") == 0 )
      {
           if (CathegoryTree.getSelectionPath()!=null && priceDAO.isColumn((DefaultMutableTreeNode)CathegoryTree.getSelectionPath().getLastPathComponent()))
           {
                priceDAO.removeColumn( (DefaultMutableTreeNode)CathegoryTree.getSelectionPath().getLastPathComponent()) ;
                CathegoryTree.setModel(priceDAO.getTree().getModel());
                CathegoryTree.getModel().addTreeModelListener(this);
           }
           else
           {
                 JOptionPane.showMessageDialog(null,"Не выбрано поле или выбраный элемент не поле");
           }
      }
    }//GEN-LAST:event_TreeRemoveColButtonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel ButtonPanel;
    private javax.swing.JMenuItem CategoryEditMenuItem;
    private javax.swing.JFrame CathegoryFrame;
    private javax.swing.JTree CathegoryTree;
    private javax.swing.JTextField DBLoginField;
    private javax.swing.JPasswordField DBPasswordField;
    private javax.swing.JTextField DBServerField;
    private javax.swing.JMenuItem LoadPriceItem;
    private javax.swing.JMenuItem MenuOptionsItem;
    private javax.swing.JPanel OptionsButtonPanel;
    private javax.swing.JFrame OptionsFrame;
    private javax.swing.JButton OptionsFrameCancelButton;
    private javax.swing.JButton OptionsFrameSaveButton;
    private javax.swing.JPanel TextPanel;
    private javax.swing.JPanel ThtreeButtonPanel;
    private javax.swing.JMenu ToolsMenu;
    private javax.swing.JButton TreeAddButton;
    private javax.swing.JButton TreeAddColButton;
    private javax.swing.JButton TreeCancelButton;
    private javax.swing.JButton TreeDeleteButton;
    private javax.swing.JButton TreeRemoveColButton;
    private javax.swing.JButton TreeSaveButton;
    private javax.swing.JScrollPane TreeScrollPane;
    private javax.swing.JTextArea TreeTextArea;
    private javax.swing.JTextArea historyTextArea;
    private javax.swing.JTree historyTree;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem savePriceMenuItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenuItem styleEditorMenuItem;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private PriceDAO priceDAO = new PriceDAO();

    private DocViewManager manager = new DocViewManager();

    public void treeNodesChanged(TreeModelEvent e) {
           
        DefaultMutableTreeNode node;
        node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
        int index = e.getChildIndices()[0];
        node = (DefaultMutableTreeNode)(node.getChildAt(index));
        if (!priceDAO.isColumn(node))
        {
            priceDAO.RenameCathegory(node, node.toString());
        }
        else
        {
            priceDAO.renameColumn(node, node.toString());
        }
    }

    public void treeNodesInserted(TreeModelEvent e) {
        
    }

    public void treeNodesRemoved(TreeModelEvent e) {
        
    }

    public void treeStructureChanged(TreeModelEvent e) {
        
    }
}
